/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cassys.action;

import cassys.datatransferobjects.TeamDTO;
import cassys.delegates.TeamDelegate;
import java.util.List;

/**
 *
 * @author ASUS
 */
public class TeamAction extends CassysSupport{
    
    private String teamId;
    private String moduleCode;
    private TeamDTO team;
    private List<TeamDTO> teams;
    private boolean isUpdate = false;
    private TeamDelegate teamDelegate = new TeamDelegate();

    public List<TeamDTO> getTeams() throws Exception{
        if(moduleCode.length() > 0)
            teams = teamDelegate.findAllTeamByModule(moduleCode);
        else
            teams = teamDelegate.findAllTeams();
        return teams;
    }
    
    public void setTeams(List<TeamDTO> teams){
        this.teams = teams;
    }
    
     public String list() {
        return "teamform";
    }

    public String create() throws Exception {
        isUpdate = false;
        return "teamform";
    }

    public String delete() throws Exception {
        team = findTeamById(teamId);
        teamDelegate.deleteTeam(team);
        return "success";
    }

    public String edit() throws Exception {
        team = findTeamById(teamId);
        if (team != null) {
            isUpdate = true;
        }
        return "teamform";
    }

    public String update() throws Exception {
    
        team.setModuleCode(moduleCode);
        
        if (isUpdate) {
            teamDelegate.updateTeam(team);
        } else {
            teamDelegate.insertTeam(team);
        }
        
        team = null;
        return "success";
    }
    
    public TeamDTO findTeamById(String teamId){
        TeamDTO t = null;
        try{
            t = teamDelegate.findTeambyId(teamId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return t;
    }
    
    public boolean isIsUpdate() {
        return isUpdate;
    }

    public void setIsUpdate(boolean isUpdate) {
        this.isUpdate = isUpdate;
    }

    public TeamDTO getTeam() {
        return team;
    }

    public void setTeam(TeamDTO team) {
        this.team = team;
    }

    public String getTeamId() {
        return teamId;
    }

    public void setTeamId(String teamId) {
        this.teamId = teamId;
    }
    
     public String getModuleCode() {
        return moduleCode;
    }

    public void setModuleCode(String moduleCode) {
        this.moduleCode = moduleCode;
    }
    
    @Override
    public void validate() {
        if (team != null) {
            if (team.getTeamId().trim().length() == 0) {
                addFieldError("team.teamId", "Team Id is required");
            }
            if (team.getSize() == 0 || team.getSize() < 0) {
                addFieldError("team.size", "Team Size is required");
            }
        }
    }
}
